library(readxl)
library(ggplot2)
library(tidyverse)


fpth <- file.path('JH_firmtype_625_1.0.xlsx')
df <- read_excel(fpth, sheet = "long")

df$m <- 0
df$m[df$firmtype == "PD"] <- df$prob_inlanddomestic[df$firmtype == "PD"]
df$m[df$firmtype == "CI"] <- df$prob_coastexporter[df$firmtype == "CI"]
df$m[df$firmtype == "CD"] <- df$prob_coastexporter[df$firmtype == "CD"]
df$m[df$firmtype == "PI"] <- df$prob_coastexporter[df$firmtype == "PI"]
df$type = "Exit"
df$type[df$firmtype == "PD"] <- "Periphery-Domestic"
df$type[df$firmtype == "PI"] <- "Periphery-Exporter"
df$type[df$firmtype == "CI"] <- "Core-Exporter"
df$type[df$firmtype == "CD"] <- "Core-Domestic"
phi_del <- read_excel(fpth) 
phi_del$qt <- seq_len(nrow(phi_del))
df$phi <- round(df$phi, 4)
df$del <- round(df$del, 4)
phi_del$phi <- round(phi_del$phi, 4)
phi_del$del <- round(phi_del$del, 4)
df <- merge(df, phi_del[, c("phi", "qt")], by = "phi")
names(df)[names(df) == "qt"] <- "phi_qt"
df <- merge(df, phi_del[, c("del", "qt")], by = "del")
names(df)[names(df) == "qt"] <- "del_qt"

ordered_leg <- c("Exit", "Periphery-Domestic", "Periphery-Exporter", "Core-Domestic", "Core-Exporter")
df$m[df$type == "Exit"] <- 0.5
ggplot(df, aes(del_qt * 4, phi_qt * 4, size = m, shape = type, color = type)) +
    geom_point(alpha = 0.9, stroke = 3) + scale_size(range = c(0, 10)) +
    scale_color_manual(values = c("Exit" = "black", "Periphery-Domestic" = "#1f78b4", "Periphery-Exporter" = "orange", "Core-Domestic" = "#33a02c" , "Core-Exporter" = "#fb9a99"),
        breaks = ordered_leg) +
    scale_shape_manual(values = c("Exit" = 4, "Periphery-Domestic" = 1, "Periphery-Exporter" = 8, "Core-Domestic" = 0, "Core-Exporter" = 2),
        breaks = ordered_leg) +
    theme_bw() + guides(size = "none") +
    labs(x = "Size", y = "Efficiency", shape = NULL, color = NULL) +
    theme(legend.position = "bottom", text=element_text(size=20))
    
ggsave("firm_probs_qt_625_1.svg", device = "svg", dpi = 320)
ggsave("firm_probs_qt_625_1.pdf", device = "pdf", dpi = 320)


# plot emission, intensity, dirty input, abate share and dirty input to intermediate rate plots as well?

ordered_leg <- c("Exit", "Periphery-Domestic", "Periphery-Exporter", "Core-Domestic", "Core-Exporter")
df$m[df$type == "Exit"] <- 0.5
df$fill_var <- 0
vals <- quantile(df[df$type != "Exit", "emission"], probs = seq(0, 1, 0.1))[c(2, 10)]
df$fill_var[df$type != "Exit" & df$emission > vals[2]] <- 1 
df$fill_var[df$type != "Exit" & df$emission < vals[1]] <- 1


# m <- df[df$type != "Exit" & df$emission < vals[1], c('phi_qt', 'del_qt')]
m <- df[df$type == "Exit", c('phi_qt', 'del_qt')]
m$phi_qt <- m$phi_qt * 4
m$del_qt <- m$del_qt * 4
hull <- chull(m) #create coordinates of convex hull
coords <- m[ c( hull, hull[1]), ]  
# coords$del_qt[coords$del_qt != 44] <- coords$del_qt[coords$del_qt != 44] + 3
# coords$del_qt[coords$del_qt == 44] <- 42
# coords$phi_qt[coords$phi_qt != 32] <- coords$phi_qt[coords$phi_qt != 32] - 1
# coords$phi_qt[coords$phi_qt == 32] <- 34
lb_y <- mean(m$phi_qt)
lb_x <- mean(m$del_qt)


m <- df[df$type != "Exit" & df$emission > vals[2], c('phi_qt', 'del_qt')]
m$phi_qt <- m$phi_qt * 4
m$del_qt <- m$del_qt * 4
add <- df[df$type == "Core-Domestic" & df$emission > vals[2], c('phi_qt', 'del_qt')]
add$phi_qt <- add$phi_qt * 4
add$del_qt <- add$del_qt * 4

hull <- chull(m) #create coordinates of convex hull
coords_upper <- rbind(m[hull[1], ], add, m[hull[c(2, 3, 1)], ])
lb_uy <- mean(m$phi_qt)
lb_ux <- mean(m$del_qt)

exit_x <- mean(df[df$type == "Exit", "del_qt"]) * 4
exit_y <- mean(df[df$type == "Exit", "phi_qt"]) * 4
# coords$del_qt[coords$del_qt != 44] <- coords$del_qt[coords$del_qt != 44] + 3
# coords$del_qt[coords$del_qt == 44] <- 42
# coords$phi_qt[coords$phi_qt != 32] <- coords$phi_qt[coords$phi_qt != 32] - 1
# coords$phi_qt[coords$phi_qt == 32] <- 34
# lb_y <- mean(m$phi_qt)
# lb_x <- mean(m$del_qt)


ggplot(df[df$type != "Exit", ], aes(del_qt * 4, phi_qt * 4, fill = factor(fill_var),
            size = emission, shape = type, color = type)) +
    geom_point(alpha = 0.9, stroke = 2.5) + scale_size(range = c(1.5, 20)) +
    scale_color_manual(values = c("Exit" = "#1f78b4", "Periphery-Domestic" = "black", "Periphery-Exporter" = "orange", "Core-Domestic" = "#33a02c" , "Core-Exporter" = "#fb9a99"),
        breaks = ordered_leg) +
    scale_shape_manual(values = c("Exit" = 21, "Periphery-Domestic" = 4, "Periphery-Exporter" = 8, "Core-Domestic" = 22, "Core-Exporter" = 24),
        breaks = ordered_leg) +
    geom_polygon(data = coords, aes(del_qt, phi_qt), color = "darkgrey",
                   size = 1, linetype = "dashed",  fill = 'grey', alpha = 0.25, inherit.aes = F) +
    geom_polygon(data = coords_upper,
                    aes(del_qt, phi_qt), color = "black",
                   size = 1, fill = NA, alpha = 0.25, inherit.aes = F) +
    scale_fill_manual(values = c("white", "darkgrey")) + 
    theme_bw() + guides(size = "none", fill = "none") +
    # annotate("text", x = lb_x, y = lb_y, label = "Bottom 10%", size = 10) +
    annotate("text", x = lb_ux, y = lb_uy, label = "Top 10%", size = 10) +
    annotate("text", x = exit_x, y = exit_y, label = "Exit", size = 20) +
    labs(x = "Size", y = "Efficiency", shape = NULL, color = NULL) +
    theme(legend.position = "bottom", text=element_text(size=20))

ggsave("/Users/jbhoward/Desktop/JAERE Extension/new plots/emissions_qt_625_1.svg", device = "svg", dpi = 320)
ggsave("/Users/jbhoward/Desktop/JAERE Extension/new plots/emissions_qt_625_1.pdf", device=cairo_pdf, family="Arial Unicode MS", dpi = 320)


ggplot(df, aes(del_qt * 4, phi_qt * 4,
            size = emission, shape = type, color = type)) +
    geom_point(alpha = 0.9, stroke = 3) + scale_size(range = c(0, 20)) +
    scale_color_manual(values = c("Exit" = "black", "Periphery-Domestic" = "#1f78b4", "Periphery-Exporter" = "orange", "Core-Domestic" = "#33a02c" , "Core-Exporter" = "#fb9a99"),
        breaks = ordered_leg) +
    scale_shape_manual(values = c("Exit" = 4, "Periphery-Domestic" = 21, "Periphery-Exporter" = 8, "Core-Domestic" = 22, "Core-Exporter" = 24),
        breaks = ordered_leg) +
    geom_polygon(data = coords, aes(del_qt, phi_qt), color = "darkgrey", size = 1, fill = 'grey', alpha = 0.25, inherit.aes = F) +
    theme_bw() + guides(size = "none") +
    labs(x = "Size", y = "Efficiency", shape = NULL, color = NULL) +
    theme(legend.position = "bottom", text=element_text(size=20))



fpth <- file.path("JH_firmtype_625_1.5.xlsx")
df <- read_excel(fpth, sheet = "long")
phi_del <- read_excel(fpth) 
phi_del$qt <- seq_len(nrow(phi_del))
df$phi <- round(df$phi, 4)
df$del <- round(df$del, 4)
phi_del$phi <- round(phi_del$phi, 4)
phi_del$del <- round(phi_del$del, 4)
df <- merge(df, phi_del[, c("phi", "qt")], by = "phi")
names(df)[names(df) == "qt"] <- "phi_qt"
df <- merge(df, phi_del[, c("del", "qt")], by = "del")
names(df)[names(df) == "qt"] <- "del_qt"


df <- df %>% rowwise() %>% mutate(m = max(c(prob_inlanddomestic, prob_inlandexporter, prob_coastdomestic, prob_coastexporter)))

df$type <- "Exit"
df$type[df$prob_inlanddomestic == df$m & df$m != 0] <- "Periphery-Domestic"
df$type[df$prob_inlandexporter == df$m & df$m != 0] <- "Periphery-Exporter"
df$type[df$prob_coastdomestic == df$m & df$m != 0] <- "Core-Domestic"
df$type[df$prob_coastexporter == df$m & df$m != 0] <- "Core-Exporter"


ordered_leg <- c("Exit", "Periphery-Domestic", "Periphery-Exporter", "Core-Domestic", "Core-Exporter")
df$m[df$type == "Exit"] <- 0.5
ggplot(df, aes(del_qt * 4, phi_qt * 4, size = m, shape = type, color = type)) +
    geom_point(alpha = 0.9, stroke = 3) + scale_size(range = c(0, 10)) +
    scale_color_manual(values = c("Exit" = "black", "Periphery-Domestic" = "#1f78b4", "Periphery-Exporter" = "orange", "Core-Domestic" = "#33a02c" , "Core-Exporter" = "#fb9a99"),
        breaks = ordered_leg) +
    scale_shape_manual(values = c("Exit" = 4, "Periphery-Domestic" = 1, "Periphery-Exporter" = 8, "Core-Domestic" = 0, "Core-Exporter" = 2),
        breaks = ordered_leg) +
    theme_bw() + guides(size = "none") +
    labs(x = "Size", y = "Efficiency", shape = NULL, color = NULL) +
    theme(legend.position = "bottom", text=element_text(size=20))
    
ggsave("firm_probs_qt_625_1.5.svg", device = "svg", dpi = 320)
ggsave("firm_probs_qt_625_1.5.pdf", device = "pdf", dpi = 320)












# tmp <- excel_sheets(fpth)
# tmp <- tmp[2:length(tmp)]
# df <- list()
# phi_del <- read_excel(fpth) 
# counter <- 0
# for (sn in tmp) {
#     counter <- counter + 1
#     df1 <- read_excel(fpth, sheet = sn, col_names = F, col_types = "numeric")
#     df1 <- df1[1:15, ]
#     names(df1) <- paste0("del_", 1:15)
#     df1$phi_qt <- rownames(df1)
#     df1 <- df1 %>% 
#         pivot_longer(cols = starts_with('del_'),
#             names_to = 'del_qt', values_to = sn)
#     df1$del_qt <- as.numeric(gsub("del_", "", df1$del_qt))
#     df[[counter]] <- df1
# }

# df <- df %>% reduce(inner_join, by = c("del_qt", "phi_qt"))
# df$del_qt <- as.numeric(df$del_qt)
# df$phi_qt <- as.numeric(df$phi_qt)
# phi_del$qt <- 1:15

# df <- merge(df, phi_del[, c("phi", "qt")], by.x = "phi_qt", by.y = "qt")
# df <- merge(df, phi_del[, c("del", "qt")], by.x = "del_qt", by.y = "qt")

# df <- df %>% rowwise() %>% mutate(m = max(c(prob_inlanddomestic, prob_inlandexporter, prob_coastdomestic, prob_coastexporter)))

# df$type <- "Exit"
# df$type[df$prob_inlanddomestic == df$m & df$m != 0] <- "Periphery-Domestic"
# df$type[df$prob_inlandexporter == df$m & df$m != 0] <- "Periphery-Exporter"
# df$type[df$prob_coastdomestic == df$m & df$m != 0] <- "Core-Domestic"
# df$type[df$prob_coastexporter == df$m & df$m != 0] <- "Core-Exporter"



# ordered_leg <- c("Exit", "Periphery-Domestic", "Periphery-Exporter", "Core-Domestic", "Core-Exporter")

# df$m[df$type == "Exit"] <- 0.8
# ggplot(df, aes(del_qt, phi_qt, size = m, shape = type, color = type)) +
#     geom_point(alpha = 0.9, stroke = 3) + scale_size(range = c(0, 15)) +
#     scale_color_manual(values = c("#33a02c" , "#fb9a99", "black", "#1f78b4", "#b2df8a", "#a6cee3"),
#         breaks = ordered_leg) +
#     scale_shape_manual(values = c(4, 1, 7, 0, 2), breaks = ordered_leg) +
#     theme_bw() + guides(size = "none") +
#     labs(x = "Size", y = "Efficiency", shape = NULL, color = NULL) +
#     theme(legend.position = "bottom", text=element_text(size=20))


    
# ggsave("combined_example_qt.svg", device = "svg", dpi = 320)




# ggplot(df, aes(phi_qt, del_qt, size = prob_inlanddomestic)) +
#     geom_point(alpha = 0.5, shape = 20, show.legend  = F) +
#     scale_size(range = c(0, 40))
# ggsave("inlanddomestic_example.png")


# ggplot(df, aes(phi_qt, del_qt, size = prob_inlandexporter)) +
#     geom_point(alpha = 0.5, shape = 20) +
#     scale_size(range = c(0, 40)) + 
#     theme_minimal() +
#     theme(legend.position = "bottom") 

# ggsave("inlandexporter_example.png")
